package com.tansun.easycare.rule.table.decisiontable.web;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.tansun.easycare.rule.common.BomCreator;
import com.tansun.easycare.rule.common.JsonMessage;
import com.tansun.easycare.rule.common.ResMessage;
import com.tansun.easycare.rule.common.RuleBaseController;
import com.tansun.easycare.rule.common.model.Bom;
import com.tansun.easycare.rule.common.model.Domain;
import com.tansun.easycare.rule.common.service.DataBomService;
import com.tansun.easycare.rule.rulemange.entity.RuleManage;
import com.tansun.easycare.rule.rulemange.model.RuleManageVO;
import com.tansun.easycare.rule.rulemange.service.RuleManageService;
import com.tansun.easycare.rule.table.decisiontable.model.DecisionTableItem;
import com.tansun.easycare.rule.table.decisiontable.model.DecisionTableRow;
import com.tansun.easycare.rule.table.decisiontable.model.TableEntity;
import com.tansun.easycare.rule.table.decisiontable.service.DecisionTableService;
import com.tansun.easycare.rule.table.entity.RuleDecisiontableDetail;
import com.tansun.easycare.rule.utils.JsonUtil;
import com.tansun.rule.common.RuleModelTypeEnum;
import com.tansun.rule.utils.LoggerManager;
import com.tansun.rule.utils.StringUtils;

@Controller
@RequestMapping(value = "/ruleProj/decisionTable")
public class DecisionTableController extends RuleBaseController {

    @Autowired
    private DecisionTableService decisionTableService;

    @Autowired
    private RuleManageService ruleManageService;

    @Autowired
    private DataBomService dataBomService;


    /**
     * 进入决策表模型管理页面
     *
     * @param param 搜索参数模型
     * @return 路径信息
     */
    @RequestMapping("index")
    public String index(HttpServletRequest request, HttpServletResponse response, RuleManageVO param, ModelMap map) throws Exception {
        param.setProjectCode(this.getCurrProjectCode());
        param.setModelType(RuleModelTypeEnum.DecisionTable.getCode());

        PageInfo<RuleManageVO> page = this.ruleManageService.findRuleManageVO(param.getPage(), param);
        map.put("page", page);
        map.put("rankRelationId", param.getRankRelationId());
        map.put("vo", JsonUtil.bean2json(param));
        map.put("projectCode", this.getCurrProjectCode());
        return "rule/table/decisiontable/index";
    }

    /**
     * 进去决策表详情也变
     *
     * @param projectCode   规则项目编号
     * @param decisionTblId 决策表ID
     * @param isedit        处于编辑状态还是查看状态，display，edit
     * @return 页面路径
     */
    @RequestMapping("detail")
    public String detail(HttpServletRequest request, String projectCode, String decisionTblId,String rankRelationId,String version, String isedit, ModelMap map, String temp) throws Exception {
    	RuleManage desTable = ruleManageService.get(decisionTblId);
        if(desTable==null){
        	desTable = ruleManageService.findByCode(decisionTblId, this.getCurrProjectCode());
        }
        if(StringUtils.isNotEmpty(version)){
        	desTable.setVersion(version);
        }
        map.put("projectCode", projectCode);
        map.put("decisionTbl", desTable);
        map.put("isedit", isedit);
        map.put("rankRelationId", rankRelationId);
        map.put("temp", temp);
        return "rule/table/decisiontable/decisionTblDetail";
    }


    /**
     * 获取Domain下拉选项
     *
     * @return 返回是否成功对象，成功则返回变量的离散值信息
     */
    @RequestMapping("getAttribute")
    public @ResponseBody
    JsonMessage getAttribute(HttpServletRequest request) throws Exception {
        JsonMessage ret = new JsonMessage();
        try {
            String projectCode = this.getCurrProjectCode();
            Map<String, Domain> map = this.dataBomService.findDomainByProjectCode(projectCode);
            String attrs = JSON.toJSONString(map);
            ret.setData(attrs);
        } catch (Exception e) {
            LoggerManager.error("", e, this.getClass());
            ret.setResult(false);
            ret.setMessage("获取数据模型失败");
        }
        return ret;
    }

    /**
     * 获取变量参数
     *
     * @return 返回是否成功对象，成功则包含变量信息
     */
    @RequestMapping("getParameter")
    public @ResponseBody
    JsonMessage getParameter(HttpServletRequest request) throws Exception {
        JsonMessage ret = new JsonMessage();
        try {
            String projectCode = this.getCurrProjectCode();
            Map<String, Bom> map = this.dataBomService.findBomMapByProjectCode(projectCode,null);
            String attrs = BomCreator.initTopBom(map);
            ret.setData(attrs);
        } catch (Exception e) {
            LoggerManager.error("", e, this.getClass());
            ret.setResult(false);
            ret.setMessage("获取数据模型失败");
        }
        return ret;
    }

    /**
     * 决策表保存或更新
     *
     * @param tableEntity 包含模型及决策表信息
     * @return 返回是否保存成功
     */
    @RequestMapping("saveOrUpdate")
    public @ResponseBody
    JsonMessage saveOrUpdate(@RequestBody TableEntity tableEntity) throws Exception {
        JsonMessage ret = new JsonMessage();
        try {
            decisionTableService.saveOrUpdate(tableEntity);
        } catch (Exception e) {
            LoggerManager.error("", e, this.getClass());
            ret.setMessage(e.getMessage());
            ret.setResult(false);
        }
        return ret;
    }
    
    /**
     * 决策表显示java代码
     *
     * @param tableEntity 包含模型及决策表信息
     * @return 返回是否保存成功
     */
    @RequestMapping("showJavaCode")
    public @ResponseBody
    ResMessage showJavaCode(@RequestBody TableEntity tableEntity) throws Exception {
    	ResMessage res = new ResMessage();
    	String javacode = decisionTableService.showJavaCode(tableEntity);
        res.setCode("success");
        res.setMsg(javacode);
        return res;
    }
    

    /**
     * 规则决策表详情
     *
     * @param decisionTblId 决策表ID
     * @param version       版本号（为空时取最新版本）
     * @return 返回决策表信息
     */
    @RequestMapping("getTableDetail")
    public @ResponseBody
    JsonMessage getTableDetail(HttpServletRequest request, String decisionTblId, String temp, @RequestParam(value = "version", required = false) String version) throws Exception {
        JsonMessage ret = new JsonMessage();
        try {
            RuleDecisiontableDetail ruleDecisiontableDetail = new RuleDecisiontableDetail();
            ruleDecisiontableDetail.setManageId(decisionTblId);
            if (StringUtils.isEmpty(version)) {
                RuleManage tmpManage = ruleManageService.get(decisionTblId);
                if (tmpManage != null) {
                    ruleDecisiontableDetail.setVersion(tmpManage.getVersion());
                }
                if("1".equals(temp)) {
                	ruleDecisiontableDetail.setVersion(tmpManage.getActiveVersion());
                }
            } else {
                ruleDecisiontableDetail.setVersion(version);
            }
            List<RuleDecisiontableDetail> list = this.decisionTableService.findList(ruleDecisiontableDetail);
            List<DecisionTableRow> decisionItemList = new ArrayList<DecisionTableRow>();
            DecisionTableRow decisionTableRow = null;
            DecisionTableItem tableItem = null;
            RuleDecisiontableDetail decisiontableDetail = null;
            Map<String, DecisionTableRow> mapList = new HashMap<String, DecisionTableRow>();
            for (int i = 0; i < list.size(); i++) {
                decisiontableDetail = list.get(i);
                if (mapList.containsKey(String.valueOf(decisiontableDetail.getRowNo()))) {
                    decisionTableRow = mapList.get(String.valueOf(decisiontableDetail.getRowNo()));
                } else {
                    decisionTableRow = new DecisionTableRow();
                    decisionTableRow.setRowIndex(decisiontableDetail.getRowNo());
                    decisionTableRow.setRowItems(new ArrayList<DecisionTableItem>());
                    mapList.put(String.valueOf(decisiontableDetail.getRowNo()), decisionTableRow);
                }
                tableItem = new DecisionTableItem();
                tableItem.setNameCN(decisiontableDetail.getNamecn());
                tableItem.setNameEN(decisiontableDetail.getNameen());
                BeanUtils.copyProperties(tableItem, decisiontableDetail);
                decisionTableRow.getRowItems().add(tableItem);
            }
            for (Map.Entry<String, DecisionTableRow> entry : mapList.entrySet()) {
                decisionItemList.add(entry.getValue());
            }
            Collections.sort(decisionItemList);
            ret.setData((Serializable) decisionItemList);
        } catch (Exception e) {
            LoggerManager.error("", e, this.getClass());
            ret.setResult(false);
            ret.setMessage("规则信息获取失败，请查看日志");
        }
        return ret;
    }


    /**
     * 将决策表转换决策树或者一维表
     *
     * @param id   决策表ID
     * @param type 转换类型(tree:转换决策树,singleTblIndex:一维表索引)
     * @return 返回是否成功信息
     */
    @RequestMapping("transfer")
    public @ResponseBody
    JsonMessage transfer(String id, String type,String rankRelationId) throws Exception {
        JsonMessage ret = new JsonMessage();
        try {
            if ("tree".equals(type))
                decisionTableService.transferToTree(id,rankRelationId);
            else
                decisionTableService.transferToSingleTbl(id,rankRelationId);
        } catch (Exception e) {
            LoggerManager.error("", e, this.getClass());
            ret.setResult(false);
            ret.setMessage(e.getMessage());
        }
        return ret;
    }

    @Override
    public void setRuleBizService() {
        super.setRuleBaseService(this.decisionTableService);
    }
}
